IMAGEFILE=demo.tar
VERSION=0.0.1
usage(){
    cat <<EOF

    Usage: deploy [OPTION] [command]
    Options:

    -f, --file           image file path (default xyserver.tar)
    -p, --port           map server port to <port> (default 9044)
    -h, --help           help information
    -v, --version        image build version(default 0.0.1)

    Commands:

    reload               reloall
    stop                 stop server
    start                start server
    build                build image
EOF
}


set_image_file() {
    test -e $1 || echo "file invalid"
    IMAGEFILE=$1
}

set_image_version(){
    VERSION=$1
}

start_server() {
    docker load -i ${IMAGEFILE}
    docker start demo
}



build_server() {
    docker build  -t demo:${VERSION} .
    docker save demo:${VERSION} > demo_${VERSION}.tar
    # docker rmi $(docker images -f "dangling=true" -q) #删除<none> 镜像   不要加
}


stop_server() {
    docker stop demo
}


reload_server() {
    docker rm -f demo #del container
    docker images | grep 'demo' | awk '{print $3}' | xargs docker rmi -f
    docker load -i ${IMAGEFILE}
    local imaegid=`docker images |grep 'demo' | awk '{print $3}' `
    docker run -d --name demo -v logs:/logs -p 9981:9981 ${imaegid}
    local PId=`lsof -i:9981|grep -v "PID" | awk '{print $2}'`
    test "$PId" == "" || echo "reload failed" 1>&2
    echo "reload completed"
}

while test $# -ne 0; do
    arg=$1;shift
    case "$arg" in 
        -h|--help) usage; exit;;
        -f|--file) set_image_file $1; shift;;
        -v|--version) set_image_version $1; shift;;
        reload) reload_server;exit;;
        start) start_server; exit;;
        stop) stop_server; exit;;
        build) build_server; exit;;
    esac
done